#include "kernel/types.h"
#include "user/user.h"

int main(int argc, char *argv[])
{
    int pipefd1[2];
    int pipefd2[2];

    if (pipe(pipefd1) == -1)
    {
        fprintf(2, "pipe error");
        exit(1); // 创建管道1错误
    }
    if (pipe(pipefd2) == -1)
    {
        fprintf(2, "pipe error");
        exit(1);
    }

    int PID;
    char buffer[1];
    // 进程标识符和要进行传输的单个字节

    // fork子进程
    PID = fork();
    if (PID == -1)
    {
        fprintf(2, "fork error");
        exit(1);
    }
    else if (PID == 0)
    {
        // 子进程
        // 关闭pipe1的写和pipe2的读
        close(pipefd1[1]);
        close(pipefd2[0]);

        // 从pipe1里面读 往pipe2里面写
        read(pipefd1[0], buffer, 1);
        printf("%d: received ping\n", getpid());

        write(pipefd2[1], buffer, 1);
        // 再把pipe1的读和pipe2的写也关上
        close(pipefd1[0]);
        close(pipefd2[1]);
        exit(0);
    }
    else
    {
        // 父进程
        close(pipefd1[0]);
        close(pipefd2[1]);

        // 从pipe2里面读 往pipe1里面写
        write(pipefd1[1], "A", 1); // 写入一个字节
        read(pipefd2[0], buffer, 1);
        printf("%d: received pong\n", getpid());

        close(pipefd1[1]);
        close(pipefd2[0]);
        exit(0);
    }
}
